<template>
  <page-header-wrapper>
    <a-card :loading="loading" :bordered="false" class="card_top_padding no_need_padding" style="margin-bottom: 11px">
      <a-tabs :default-active-key="settingInfo[0].key" v-if="settingInfo.length > 0" @change="changeTabs">
        <a-tab-pane
          :tab="settingItem.name"
          v-for="(settingItem, itemIndex) of settingInfo"
          v-if="$auth('settingEdit.' + settingItem.key)"
          :key="settingItem.key"
        >
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <a-card :bordered="false">
      <div v-for="(settingItem, itemIndex) of settingInfo" :key="settingItem.key" v-if="settingItem.key == currentTab">
        <a-row :gutter="[24, 20]" v-for="(infoItem, infoIndex) in settingItem.list" :key="infoIndex">
          <template v-if="!infoItem.hide">
            <a-divider v-if="infoItem.title">{{ infoItem.title }}</a-divider>
            <a-col :span="3" style="text-align: right" :class="infoItem.required ? 'required' : ''">
              {{ infoItem.text }}：
            </a-col>
            <a-col :span="21">
              <div v-if="infoItem.type == 'coordinate'">
                <a-input disabled :value="infoItem.value" style="width: 200px; margin-right: 10px" />
                <a-button type="primary" @click="onClickSelectMap(infoItem)"> 选择 </a-button>
              </div>
              <div v-if="infoItem.type == 'address_info'" class="address">
                <Address :value="infoItem.value" @input="(e) => (infoItem.value = e)"></Address>
              </div>
              <a-input
                v-if="['text', 'number', 'textarea', 'mobile'].indexOf(infoItem.type) > -1"
                :type="infoItem.type"
                :placeholder="'请填写' + infoItem.text"
                v-model="settingInfo[itemIndex].list[infoIndex].value"
                :suffix="infoItem.unit"
              />
              <a-select
                v-if="infoItem.type == 'select'"
                style="width: 300px"
                v-model="settingInfo[itemIndex].list[infoIndex].value"
              >
                <a-select-option v-for="article in articleList" :key="article.id">
                  {{ article.name }}
                </a-select-option>
              </a-select>
              <a-select
                v-if="infoItem.type == 'language'"
                style="width: 300px"
                v-model="settingInfo[itemIndex].list[infoIndex].value"
              >
                <a-select-option v-for="(item, index) in languages" :key="index" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <a-radio-group
                v-if="infoItem.type == 'radio'"
                :name="infoItem.name"
                :default-value="settingInfo[itemIndex].list[infoIndex].value > 0 ? 1 : 0"
                v-model="settingInfo[itemIndex].list[infoIndex].value"
              >
                <template v-if="settingInfo[itemIndex].list[infoIndex].select_list.length > 0">
                  <a-radio
                    v-for="select in settingInfo[itemIndex].list[infoIndex].select_list"
                    :key="select.value + ''"
                    :value="select.value + ''"
                  >
                    {{ select.key }}
                  </a-radio>
                </template>
                <template v-else>
                  <a-radio :value="'0'"> 关闭 </a-radio>
                  <a-radio :value="'1'"> 开启 </a-radio>
                </template>
              </a-radio-group>
              <div v-if="infoItem.type == 'checkbox'" :name="infoItem.name">
                <a-checkbox
                  v-for="(checkItem, checkIndex) of infoItem.value"
                  :key="checkIndex"
                  :value="checkIndex"
                  @change="onChange(itemIndex, infoIndex, checkIndex)"
                  :defaultChecked="checkItem.value == '1' ? true : false"
                  :checked="checkItem.value == '1' ? true : false"
                >
                  {{ checkItem.text }}
                </a-checkbox>
              </div>
              <!-- <a-input
                v-if="['image'].indexOf(infoItem.type) > -1"
                type="text"
                :placeholder=" '请填写' + infoItem.text"
                v-model="settingInfo[itemIndex].list[infoIndex].value"
                :suffix="infoItem.unit" /> -->
              <!-- <storage-select
                v-if="['image'].indexOf(infoItem.type) > -1"
                :placeholder="'请填写' + infoItem.text"
                :sizeTips="settingInfo[itemIndex].list[infoIndex].size"
                v-model="settingInfo[itemIndex].list[infoIndex].value"
              ></storage-select> -->
              <cyyUploadImg
                v-if="['image'].indexOf(infoItem.type) > -1"
                @uploadSuccess="
                  (e) => {
                    settingInfo[itemIndex].list[infoIndex].value = e.data
                  }
                "
                @deleteImg="settingInfo[itemIndex].list[infoIndex].value = ''"
                :imgSrc="settingInfo[itemIndex].list[infoIndex].value"
                :imgSizeText="settingInfo[itemIndex].list[infoIndex].size"
              >
              </cyyUploadImg>

              <div v-if="infoItem.type == 'file'">
                <div class="flexApk">
                  <a-input v-model="settingInfo[itemIndex].list[infoIndex].value" disabled />

                  <a-upload
                    class="btn"
                    name="apk"
                    accept=".apk"
                    :action="upload_url"
                    :headers="upload_headers"
                    :showUploadList="false"
                    @change="(e) => onUploadChange(settingInfo[itemIndex].list[infoIndex], e)"
                  >
                    <a-button> <a-icon type="upload" />上传 </a-button>
                  </a-upload>

                  <a-button class="btn" type="danger" @click="settingInfo[itemIndex].list[infoIndex].value = ''">
                    删除
                  </a-button>
                </div>
                <div style="width: 400px">
                  <a-progress v-if="progress" :percent="progress" />
                </div>
              </div>
              <a-row style="font-size: 12px" v-if="infoItem.muted" v-html="infoItem.muted"></a-row>
            </a-col>
          </template>
        </a-row>
        <div style="text-align: center">
          <a-button @click="saveInfo" type="primary">保存</a-button>
        </div>
      </div>
    </a-card>

    <SelectMap
      :oldmarker="item.value"
      v-if="mapVisiable"
      :value.sync="mapVisiable"
      @onOk="(e) => (item.value = e)"
    ></SelectMap>
  </page-header-wrapper>
</template>

<script>
import { getSetting, saveSetting } from '@/api/setting/setting'
import { getAboutArticle } from '@/api/content'
import { cyyUploadImg } from '@/components/CyyUi'
import Address from '@/components/Address'
import SelectMap from '@/components/SelectMap/SelectMap'
import api from '@/api/storage'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'SettingEdit',
  components: {
    cyyUploadImg,
    Address,
    SelectMap,
  },
  data() {
    return {
      index: 0,
      settingInfo: [],
      loading: true,
      currentTab: '',
      articleList: [],
      languages: [
        { name: '中文简体', value: 'zh-CN' },
        { name: 'English', value: 'en' },
      ],

      item: {
        value: '',
      },
      mapVisiable: false,
      hasLoading: false,

      progress: 0,
      isFirst: true,
    }
  },
  created() {
    this.getInfo()
    this.article()
  },

  computed: {
    upload_url: function () {
      const baseUrl = process.env.VUE_APP_API_BASE_URL
      return baseUrl + api.upload_app
    },
    upload_headers: function () {
      const token = storage.get(ACCESS_TOKEN)
      return { Authorization: 'Bearer ' + token }
    },
  },

  watch: {
    settingInfo: {
      deep: true,
      handler(v) {
        if (v.length) {
          let list = v.find((el) => el.key === 'store')
          if (list && list.list) {
            // 控制会员积分开关
            let item = list.list.find((el) => el.text === '是否开启余额抵扣'),
              item2 = list.list.find((el) => el.text === '会员积分')

            if (item && item2) {
              if (item.value === '0') {
                item2.hide = true
              } else {
                item2.hide = false
              }
            }
          }
        }
      },
    },
  },

  methods: {
    // 上传文件改变事件
    onUploadChange(el, info) {
      console.log('info,', info)
      if (info.event) {
        if (this.isFirst) this.isFirst = false
        let { total, loaded } = info.event
        this.progress = parseInt((loaded / total) * 100) - 1
      } else {
        let url = '',
          msg = ''

        for (let i = 0; i < info.fileList.length; i++) {
          if (info.fileList[i].response) {
            if (info.fileList[i].response.code === 0) {
              let data = info.fileList[i].response.data[0]
              url = data.url

              if (data.status === false) {
                msg = data.error
                this.progress = 100

                console.log('msg,', msg)
                console.log('this.progress,', this.progress)
                console.log('this.isFirst,', this.isFirst)
                if (msg && this.progress === 100 && !this.isFirst) {
                  this.$nextTick(() => {
                    this.$message.error(msg)
                    this.isFirst = true
                    this.progress = 0
                  })
                }
                return
              }

              if (url) {
                this.$nextTick(() => {
                  el.value = url

                  this.progress = 100
                  setTimeout(() => {
                    this.progress = 0
                    this.isFirst = true
                  }, 200)
                })
              }
            }
          }
        }
      }

      // let { params } = this
      // params[el] = url
    },

    article() {
      var that = this
      return getAboutArticle({ is_have_page: 0 }).then((res) => {
        if (res.code == 0) {
          that.articleList = res.data
        }
      })
    },
    changeTabs(tab) {
      this.currentTab = tab
    },
    getInfo: function (parameter) {
      var that = this
      that.loading = true
      return getSetting(parameter).then((res) => {
        that.loading = false
        if (res.code === 0) {
          console.log(res.data)
          that.settingInfo = res.data
          that.currentTab = that.settingInfo[0].key
        } else {
          that.$message.info(res.msg)
        }
      })
    },
    saveInfo: function () {
      let { settingInfo } = this
      if (settingInfo.length) {
        let list = settingInfo.find((el) => el.key === 'store')
        if (list && list.list) {
          // 控制会员积分开关
          let item = list.list.find((el) => el.text === '会员积分')

          if (!item.hide && !item.value) {
            this.$message.error(`${item.text}不能为空~`)
            return
          }
        }
      }

      const hide = this.$message.loading('提交中', 0)
      return saveSetting({
        settingInfo: JSON.stringify(settingInfo),
      }).then((res) => {
        hide()
        if (res.code !== 0) {
          this.$warning({
            title: '内容提交失败！',
            content: res.msg,
          })
        } else {
          this.$success({
            content: res.msg,
          })
        }
      })
    },
    onChange(settingIndex, infoIndex, checkIndex) {
      var settingInfo = this.settingInfo
      settingInfo[settingIndex].list[infoIndex].value[checkIndex].value =
        settingInfo[settingIndex].list[infoIndex].value[checkIndex].value > 0 ? 0 : 1
      this.settingInfo = settingInfo
    },

    onClickSelectMap(item) {
      this.item = item
      this.mapVisiable = true
    },
  },
}
</script>
<style scoped lang="less">
.required::before {
  content: '*';
  color: red;
}
.demo-loading {
  position: absolute;
  bottom: 40px;
  width: 100%;
  text-align: center;
}

::v-deep input {
  /* 在Chrome浏览器下 */
  ::-webkit-outer-spin-button,
  ::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }
  /* 在Firefox浏览器下 */
  [type='number'] {
    -moz-appearance: textfield !important;
  }
}

.address {
  max-width: 600px;
}

.flexApk {
  display: flex;
  align-items: center;

  .btn {
    margin-left: 20px;
  }
}
</style>
